<template>
    <el-card class="matched-videos-card" v-if="videoGroups.length > 0">
        <template #header>
            <div class="card-header">
                <h2>匹配视频</h2>
                <div class="header-actions">
                    <span class="selection-count">已选择 {{ totalSelectedCount }}/{{ totalVideosCount }} 个视频</span>
                    <el-button size="small" @click="selectAll" type="primary" plain>全选</el-button>
                    <el-button size="small" @click="deselectAll" plain>取消全选</el-button>
                </div>
            </div>
        </template>

        <div v-if="loading" class="loading-container">
            <el-skeleton :rows="3" animated />
        </div>

        <div v-else-if="videoGroups.length === 0" class="empty-state">
            <el-empty description="暂无匹配视频" />
        </div>

        <div v-else>
            <!-- 添加分类标签页系统 -->
            <el-tabs v-model="activeTab" type="card">
                <!-- 为每个分类创建一个标签页 -->
                <el-tab-pane v-for="(group, groupIndex) in videoGroups" :key="`tab-${groupIndex}`"
                    :label="`${group.category} - ${group.text} (${group.videos.length})`" :name="String(groupIndex)">
                    <div class="tab-content">
                        <h3 class="prompt-group-title">
                            {{ group.category }} - {{ group.text }}
                            <span class="video-count">
                                ({{ group.videos.length }}个视频, 已选{{ getSelectedCount(groupIndex) }}个)
                            </span>
                        </h3>

                        <div class="video-grid">
                            <div v-for="video in group.videos" :key="video.id" class="video-card"
                                :class="{ 'selected': isVideoSelected(video, groupIndex) }"
                                @click="toggleVideoSelection(video, groupIndex)">
                                <!-- 视频容器 -->
                                <div class="video-container" @mouseenter="playVideo($event, video)"
                                    @mouseleave="stopVideo($event)">
                                    <div class="video-duration">{{ formatDuration(video.id) }}</div>

                                    <video :ref="el => { if (el) videoElements[video.id] = el }"
                                        :src="getVideoUrl(video)" muted loop preload="metadata" class="video-element"
                                        :controls="false" @loadedmetadata="handleVideoMetadata($event, video.id)">
                                    </video>

                                </div>
                                <!-- 视频信息 -->
                                <div class="video-info-card">
                                    <div class="title-checkbox-row">
                                        <div class="video-title" :title="video.description">
                                            {{ truncateText(video.filename, 40) }}
                                        </div>
                                        <el-checkbox :model-value="isVideoSelected(video, groupIndex)"
                                            @click.stop="toggleVideoSelection(video, groupIndex)"
                                            class="large-green-checkbox" size="large">
                                        </el-checkbox>
                                    </div>
                                    <div class="video-meta">
                                        <span class="video-filename">{{ video.username }}</span>
                                        <span class="video-date">{{ formatDate(video.created_at) }}</span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="tab-actions">
                            <el-button size="small" type="primary" @click="selectAllInCurrentTab(groupIndex)" plain>
                                全选当前分类
                            </el-button>
                            <el-button size="small" @click="deselectAllInCurrentTab(groupIndex)" plain>
                                取消当前分类选择
                            </el-button>
                        </div>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>

    </el-card>
</template>

<script>
import { defineComponent, ref, computed, watch } from 'vue';
import { genOutsideVideoURL } from '@/utils/videoHelper.js'; // 假设有一个工具函数用于生成视频URL

export default defineComponent({
    name: 'MatchedVideosPreview',
    props: {
        videoGroups: {
            type: Array,
            default: () => []
        },
        loading: {
            type: Boolean,
            default: false
        }
    },
    emits: ['update:selectedVideos'],
    setup(props, { emit }) {
        const videoElements = ref({}); // 用于存储视频元素的引用
        const selectedVideos = ref([]); // 每个组的选中视频数组
        const activeTab = ref('0'); // 当前活动的标签页
        const videoDurations = ref({}); // 用于存储视频时长

        const handleVideoMetadata = (event, videoId) => {
            const video = event.target;
            if (video && video.duration && !isNaN(video.duration)) {
                videoDurations.value[videoId] = video.duration;
            }
        };

        // 初始化选中视频数组
        const initSelectedVideos = () => {
            selectedVideos.value = props.videoGroups.map(() => []);

            // 如果有视频组但当前没有选定标签，设置第一个标签为活动标签
            if (props.videoGroups.length > 0) {
                activeTab.value = '0';
            }
        };

        // 监听 videoGroups 变化初始化 selectedVideos
        watch(() => props.videoGroups, (newGroups) => {
            initSelectedVideos();
            // 重置视频元素引用集合，防止内存泄漏
            videoElements.value = {};
        }, { immediate: true });

        // 计算总视频数量
        const totalVideosCount = computed(() => {
            return props.videoGroups.reduce((sum, group) => sum + group.videos.length, 0);
        });

        // 计算选中的视频总数量
        const totalSelectedCount = computed(() => {
            return selectedVideos.value.reduce((sum, group) => sum + group.length, 0);
        });

        // 获取特定组的选中视频数量
        const getSelectedCount = (groupIndex) => {
            return selectedVideos.value[groupIndex]?.length || 0;
        };

        // 检查视频是否被选中
        const isVideoSelected = (video, groupIndex) => {
            return selectedVideos.value[groupIndex]?.some(v => v.id === video.id) || false;
        };

        // 修改切换视频选择状态函数
        const toggleVideoSelection = (video, groupIndex, event) => {
            // 如果点击来源是复选框，则不进行额外处理（避免双重触发）
            if (event && event.target.closest('.el-checkbox')) {
                return;
            }

            if (!selectedVideos.value[groupIndex]) {
                selectedVideos.value[groupIndex] = [];
            }

            const index = selectedVideos.value[groupIndex].findIndex(v => v.id === video.id);

            if (index > -1) {
                // 已选择，移除选择
                selectedVideos.value[groupIndex].splice(index, 1);
            } else {
                // 未选择，添加选择
                selectedVideos.value[groupIndex].push(video);
            }

            // 更新父组件选择状态
            emitSelectedVideos();
        };

        // 处理视频选择变化
        const handleSelectionChange = (selection, groupIndex) => {
            selectedVideos.value[groupIndex] = selection;
            emitSelectedVideos();
        };

        // 向父组件发送选中的视频
        const emitSelectedVideos = () => {
            // 将分组后的选中视频扁平化，并添加分组信息
            const flatSelectedVideos = selectedVideos.value.flatMap((groupSelection, index) => {
                return groupSelection.map(video => ({
                    ...video,
                    promptGroup: props.videoGroups[index]
                }));
            });

            emit('update:selectedVideos', flatSelectedVideos);
        };

        // 全选所有视频
        const selectAll = () => {
            props.videoGroups.forEach((group, groupIndex) => {
                selectedVideos.value[groupIndex] = [...group.videos];
            });
            emitSelectedVideos();
        };

        // 全选当前标签页中的视频
        const selectAllInCurrentTab = (groupIndex) => {
            if (props.videoGroups[groupIndex]) {
                selectedVideos.value[groupIndex] = [...props.videoGroups[groupIndex].videos];
                emitSelectedVideos();
            }
        };

        // 取消当前标签页中的所有选择
        const deselectAllInCurrentTab = (groupIndex) => {
            if (selectedVideos.value[groupIndex]) {
                selectedVideos.value[groupIndex] = [];
                emitSelectedVideos();
            }
        };

        // 取消所有视频选择
        const deselectAll = () => {
            selectedVideos.value = selectedVideos.value.map(() => []);
            emitSelectedVideos();
        };



        // 播放视频（鼠标悬停）
        const playVideo = (event, video) => {
            const videoElement = videoElements.value[video.id];
            if (videoElement) {
                // 重置视频到开头并播放
                videoElement.currentTime = 0;

                // 显示控件 - 关键修改
                videoElement.controls = true;

                // 尝试播放
                const playPromise = videoElement.play();

                // 处理可能的错误（浏览器政策等）
                if (playPromise !== undefined) {
                    playPromise.catch(error => {
                        console.warn('自动播放被阻止:', error);
                    });
                }
            }
        };

        // 停止视频播放（鼠标离开）
        const stopVideo = (event) => {
            const videoElement = event.currentTarget.querySelector('video');
            if (videoElement) {
                // 隐藏控件 - 关键修改
                videoElement.controls = false;

                if (!videoElement.paused) {
                    videoElement.pause();
                }
            }
        };


        // 获取视频URL
        const getVideoUrl = (video) => {
            if (!video) return '';

            // 检查视频是否有本地路径
            if (video.local_path) {
                // 使用后端提供的专门视频访问路由
                return genOutsideVideoURL(video.local_path);
            }

            // 备用方案 - 检查是否有 file_path
            if (video.file_path) {
                const pathParts = video.file_path.split('\\');
                const publicIndex = pathParts.findIndex(part => part === 'public');

                if (publicIndex !== -1) {
                    // 构建URL路径
                    const relativePath = pathParts.slice(publicIndex).join('/');
                    return `${window.location.origin}/${relativePath}`;
                }
            }

            // 最后的备用选项 - 使用视频ID或文件名构建URL
            return `${window.location.origin}/search/outside_video/${video.id || video.filename || 'unknown'}`;
        };

        // 格式化时长
        const formatDuration = (videoId) => {
            // 首先尝试使用视频元数据中的时长
            const metadataDuration = videoDurations.value[videoId];
            if (metadataDuration && !isNaN(metadataDuration)) {
                const mins = Math.floor(metadataDuration / 60);
                const secs = Math.floor(metadataDuration % 60);
                return `${mins}:${secs.toString().padStart(2, '0')}`;
            }

        };

        const formatDate = (date) => {
            if (!date) return '';
            const d = new Date(date);
            return d.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        };

        // 截断文本
        const truncateText = (text, maxLength) => {
            if (!text) return '';
            return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
        };

        return {
            videoElements,
            selectedVideos,
            activeTab,
            totalSelectedCount,
            totalVideosCount,
            getSelectedCount,
            isVideoSelected,
            toggleVideoSelection,
            handleSelectionChange,
            selectAll,
            deselectAll,
            selectAllInCurrentTab,
            deselectAllInCurrentTab,
            playVideo,
            stopVideo,
            getVideoUrl,
            formatDuration,
            formatDate,
            truncateText,
            videoDurations,
            handleVideoMetadata,
        };
    }
});
</script>

<style scoped>
/* 卡片基本样式 */
.matched-videos-card {
    margin-bottom: 20px;
}

/* 卡片头部样式 */
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-actions {
    display: flex;
    align-items: center;
    gap: 10px;
}

.selection-count {
    font-size: 14px;
    color: #606266;
}

/* 分组标题样式 */
.prompt-group-title {
    margin: 10px 0;
    padding-bottom: 8px;
    border-bottom: 1px solid #ebeef5;
    font-size: 16px;
    font-weight: 500;
    color: #303133;
}

.video-count {
    font-size: 14px;
    color: #909399;
    font-weight: normal;
    margin-left: 10px;
}

/* 视频网格布局 */
.video-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 16px;
    margin-bottom: 20px;
}

/* 单个视频卡片样式 */
.video-card {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    transition: all 0.3s;
    cursor: pointer;
    position: relative;
    background-color: #f5f7fa;
    border: 2px solid transparent;
}

.video-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.15);
}

.video-card.selected {
    border-color: #409EFF;
}

/* 视频容器样式 */
.video-container {
    position: relative;
    width: 100%;
    aspect-ratio: 16 / 9;
    overflow: hidden;
    background-color: #000;
}

/* 视频元素样式 */
.video-element {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
}

/* 视频时长标签 */
.video-duration {
    position: absolute;
    bottom: 10px;
    right: 10px;
    background-color: rgba(0, 0, 0, 0.7);
    color: white;
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 12px;
    z-index: 5;
    pointer-events: none;
    transition: opacity 0.3s ease;
}

/* 视频覆盖层 */
.video-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(to bottom,
            rgba(0, 0, 0, 0.2) 0%,
            rgba(0, 0, 0, 0) 40%,
            rgba(0, 0, 0, 0) 60%,
            rgba(0, 0, 0, 0.3) 100%);
    padding: 10px;
    opacity: 0;
    transition: opacity 0.2s ease;
}

.video-container:hover .video-overlay {
    opacity: 1;
}

/* 当视频有controls属性时隐藏时长标签 */
.video-container:hover .video-duration {
    opacity: 0;
}

/* 视频信息卡片 */
.video-info-card {
    padding: 10px;
}

/* 标题与复选框行 */
.title-checkbox-row {
    display: flex;
    align-items: flex-start;
    gap: 8px;
    margin-bottom: 8px;
}

/* 视频标题样式 */
.video-title {
    font-size: 14px;
    font-weight: 500;
    line-height: 1.4;
    max-height: 40px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    flex-grow: 1;
}

/* 视频元数据 */
.video-meta {
    display: flex;
    justify-content: space-between;
    font-size: 12px;
    color: #909399;
}

.video-filename {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

/* 大绿色复选框样式 */
.large-green-checkbox {
    --el-checkbox-checked-bg-color: #67C23A;
    --el-checkbox-checked-input-border-color: #67C23A;
    --el-checkbox-checked-icon-color: #fff;
    flex-shrink: 0;
}

:deep(.large-green-checkbox .el-checkbox__inner) {
    transform: scale(1.3);
    border-radius: 4px;
}

:deep(.large-green-checkbox .el-checkbox__input.is-checked .el-checkbox__inner) {
    background-color: #67C23A;
    border-color: #67C23A;
}

/* 标签页相关样式 */
.tab-content {
    padding: 10px 0;
}

.tab-actions {
    margin-top: 15px;
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

:deep(.el-tabs__header) {
    margin-bottom: 15px;
}

:deep(.el-tabs__item) {
    height: 40px;
    line-height: 40px;
}

/* 加载和空状态 */
.loading-container {
    padding: 20px 0;
}

.empty-state {
    padding: 30px 0;
}

/* 视频控件显示逻辑 - 关键部分 */
/* 默认情况下不显示控件 */
.video-element:not([controls]) {
    -webkit-user-select: none;
    user-select: none;
}

/* 确保控件正确显示 */
.video-element[controls] {
    z-index: 10;
}

/* 解决某些浏览器控件可能一直显示的问题 */
.video-element:not([controls])::-webkit-media-controls {
    display: none !important;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
    .video-grid {
        grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
        gap: 10px;
    }

    .video-title {
        font-size: 12px;
        height: 34px;
    }
}
</style>
